<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Vendor extends CI_Controller {

	/*
	 **************************************************************************************************
	 *
	 **************************************************************************************************
	*/
	public function __construct() {

		parent::__construct();

		$this->load->database();
		$this->load->helper( 'url' );
		$this->load->library( 'grocery_CRUD' );

	}

	/*
	 **************************************************************************************************
	 *
	 **************************************************************************************************
	*/
	public function index() {

		$this->_render_vendor_output( ( object ) array( 'output' => '', 'js_files' => array(), 'css_files' => array() ) );

		try {

			$crud = new grocery_CRUD();

			$crud->set_theme( 'datatables' );
			$crud->set_table( 'tbl_vendor' );
			$crud->set_subject( 'Vendor' );
			$crud->required_fields( 'payer_name' );
			$crud->columns( 'payer_code', 'payer_name' ); // แสดง field ในหน้า list
			$crud->fields( 'payer_code', 'payer_name' ); // แสดง field ใน form
			$crud->change_field_type( 'payer_code', 'invisible' ); // ให้ซ่อน field ในหน้า form

			$crud->callback_before_insert( array( $this, 'generate_payer_code_callback' ) );


			$output = $crud->render();
			$this->_render_vendor_output( $output );

		} catch ( Exception $e ) {

			show_error( $e->getMessage() . ' --- ' . $e->getTraceAsString() );

		}

	}

	/*
	 **************************************************************************************************
	 *
	 **************************************************************************************************
	*/
	public function _render_vendor_output( $output = null ) {

		$this->load->view( 'vendor.php', $output );

	}

	/*
	 **************************************************************************************************
	 *
	 **************************************************************************************************
	*/
	public function generate_payer_code_callback( $post_array ) {

		$query = $this->db->query( "SELECT payer_code FROM tbl_vendor ORDER BY payer_code DESC LIMIT 1" );

		if ( $query->num_rows() > 0 ) {

			$row = $query->row_array();
			// $post_array[ 'payer_code' ] ต้องกำหนดให้เห็น field นี้ที่ $crud->fields()
			$post_array[ 'payer_code' ] = 'V' . str_pad ( substr( $row[ 'payer_code' ], 1 ) + 1, 3, '0', STR_PAD_LEFT );

		} else {

			// $post_array[ 'payer_code' ] ต้องกำหนดให้เห็น field นี้ที่ $crud->fields()
			$post_array[ 'payer_code' ] = 'V001';

		}

		return $post_array;

	}

}
